<template>
  <div class="tenantMenu_main main_container add_container_table AddOrUpdate_main add_container">
    <div v-loading="loading" class="main_main">
      <div style="margin-bottom:20px" class="SearchBar_main main_main_search">
        <div v-if="this.showMaterialName" class="MaterialName">
          <span class="MaterialNameIcon el-icon-warning" />
          <div v-for="item in materialName" :key="item" class="MaterialNameName">
            <span>{{ item }}</span>
          </div>
          <div class="MaterialNameText">物料暂无库存，不可选择！</div>
        </div>
        <div v-else />
        <div class="main_main_search_item">
          <el-input v-model="pageData.searchValue" class="search_input" placeholder="请输入订单号或物料编码" clearable @keyup.enter.native="()=>{pageData.pageNum=1; search()}" @clear="getList" />
          <el-button class="button_icon" icon="el-icon-search" @click.stop="()=>{pageData.pageNum=1; search()}" />
        </div>
      </div>
      <div ref="table_container" class="table_container">

        <el-table
          ref="table"
          :data="tableData"
          stripe
          border

          :cell-style="cellStyle"
          :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
          :span-method="objectSpanMethod"
          @sort-change="(column)=>{sortChange(column, this)}"
          @selection-change="(val)=>{selectionChange(val, this)}"
        >
          <el-table-column type="selection" align="center" :selectable="tableSelectable" />
          <Column v-for="(column,index) in defaultTableColumns" :key="index" :prop="column.prop" :is-show="column.isShow" :label="column.label" :sortable="column.sortable" :width="column.width" />
        </el-table>
      </div>
    </div>
    <!-- <div class="addtype-main_bottoms">
      <pagination
        :total="total"
        :page.sync="pageData.pageNum"
        :limit.sync="pageData.pageSize"
        :selected-num="selectionsAll.length"
        @pagination="getList"
      />
    </div> -->
    <div class="main_bottom">
      <el-button type="cancel" @click.stop="cancel">取消</el-button>
      <el-button @click.stop="onSubmit">保存</el-button>
    </div>
  </div>
</template>

<script>
import { getMarketInfo, getcustMarketInfo, getcustMarketInfo2 } from '@/api/saleManage/saleOrder'
export default {
  props: {
    layerid: {},
    customerNameId: {},
    selectRow: {},
    id: {}
  },
  data() {
    return {
      spanArr: [], // 存合并行数据的数组
      pos: 0, // 合并行数据数组下标
      rowIndex: 1, // 序号
      loading: false,
      pageData: {
        pageNum: 1,
        pageSize: 20,
        orderByColumn: 'updateTime',
        isAsc: 'desc',
        searchValue: '',
        id: ''
      },
      // tableKey: 1,
      total: 1, // 数据一共有多少条
      mainId: 'reverseSelectionId', // 表格行ID
      tableHeight: '0', // 表格高度
      tableData: [], // 表格数据
      tableData2: [],
      tableData3: [],
      materialName: [],
      tableDataOne: [],
      showMaterialName: false,
      tableColumns: [], // 表格实际用的字段
      searchColumns: [], // 搜索区实际用的字段
      selections: [], // 表格当前页所选中的行
      selectionsAll: [], // 表格所有页选中的行
      defaultTableColumns: [// 表格常规字段（初始值）
        { prop: 'saleOrderCode', label: '销售订单' },
        { prop: 'orderNumber', label: '订单数量' },
        { prop: 'alreadyDeliverNumber', label: '已发数量' },
        { prop: 'willDeliverNumber', label: '未发数量' },
        { prop: 'materialCode', label: '物料编码' },
        { prop: 'materialName', label: '物料名称' },
        { prop: 'materialModel', label: '规格型号' },
        { prop: 'materialUnitName', label: '物料单位' },
        { prop: 'materialInventory', label: '库存数量' }

      ]
    }
  },
  created() {
  },
  mounted() {
    console.log(this.id)
    this.pageData.id = this.id
    this.getList()
    console.log(this.selectRow)
    this.selectionsAll = this.selectRow
  },
  methods: {
    // 合并单元格
    getSpanArr(data) {
      // 重新查询后，要清空行数据数组、序号重置为1
      this.loading = true
      this.spanArr = []
      this.rowIndex = 1
      // 遍历数据，判断前后两条数据是否相同
      data.map((item, index) => {
        if (index == 0) {
          this.spanArr.push(1)
          this.pos = 0
          this.rowIndex++
        } else {
          if (item.materialCode == data[index - 1].materialCode) {
            this.spanArr[this.pos] += 1
            this.spanArr.push(0)
          } else {
            this.spanArr.push(1)
            this.pos = index
            this.rowIndex++
          }
        }
      })
      this.loading = false
    },
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 5 || columnIndex === 6 || columnIndex === 7 || columnIndex === 8 || columnIndex === 9) {
        const _row = this.spanArr[rowIndex]
        const _col = _row > 0 ? 1 : 0
        // rowspan和colspan都为0，则表示这一行不显示，[x, 1]则表示合并了多少行
        return {
          rowspan: _row,
          colspan: _col
        }
      }
    },
    cellStyle({ row, column }) {
      if (column.property == 'materialInventory') {
        if (row.materialInventory === '0') {
          return {
            color: '#E86D7C'
          }
        }
      }
    },
    tableSelectable(row, index) {
      if (row.materialInventory === '0') {
        return false
      } else {
        return true
      }
    },
    rowClick(row) {
      if (row.materialInventory !== '0') {
        this.$refs.table.toggleRowSelection(row)
      }
    },
    getList() {
      // getMarketInfo(this.id).then(res => {
      //   res.data.data.forEach(ele => {
      //     ele.saleOrderDetailId = ele.id
      //     delete ele.id
      //   })
      //   this.tableData = res.data.data
      //   this.materialName = []
      //   this.tableData.forEach(item => {
      //     if (item.materialInventory == '0') {
      //       if (this.materialName.length < 5) {
      //         this.materialName.push(item.materialName)
      //         const materialName1 = this.materialName.toString()
      //         const materialName2 = []
      //         materialName2.push(materialName1)
      //         this.materialName = materialName2
      //       } else {
      //         const materialNameOne = this.materialName.toString()
      //         const materialNameTwo = []
      //         materialNameTwo.push(materialNameOne)
      //         materialNameTwo.push('等')
      //         this.materialName = materialNameTwo
      //       }
      //       this.showMaterialName = true
      //     }
      //   })
      //   this.tableData2 = this.$deepClone(res.data.data)
      //   this.loading = false
      //   this.$nextTick(() => {
      //     this.setSelectRow(this)// 设置行选中
      //     this.tableHeight = this.$refs.table_container.offsetHeight
      //   })
      // })
      getcustMarketInfo2({ customerId: this.customerNameId, ...this.pageData }).then(res => {
        res.data.forEach(ele => {
          ele.saleOrderDetailId = ele.id
          delete ele.id
          this.selectionsAll.forEach(item => {
            if (ele.saleOrderDetailId == item.saleOrderDetailId) {
              ele.remark = item.remark
            }
          })
        })
        this.materialName = []
        const data2 = this.$deepClone(res.data)
        data2.forEach(item => {
          if (item.materialInventory == '0') {
            if (this.materialName.length < 5) {
              this.materialName.push(item.materialName + ',')
              this.materialName = this.materialNameArr(this.materialName)
            } else {
              this.materialName.push('等')
            }
            this.showMaterialName = true
          }
        })
        this.materialName = this.materialNameArr(this.materialName)
        this.Removecommas(this.materialName)
        this.tableData = data2
        this.tableData2 = this.getSpanArr(this.$deepClone(res.data))
        this.tableData3 = this.$deepClone(res.data)
        this.loading = false
        this.$nextTick(() => {
          this.setSelectRow(this)// 设置行选中
          this.tableHeight = this.$refs.table_container.offsetHeight
          console.log(this.tableHeight)
        })
      })
    },
    // 物料不足名称数组去重
    materialNameArr(arr) {
      var newArr = arr.filter(function(item, index) {
        return arr.indexOf(item) === index // 因为indexOf 只能查找到第一个
      })
      return newArr
    },
    // 去除物料名称不足最后一位逗号
    Removecommas(arr) {
      const arrTemp = arr
      if (arrTemp.length > 0) {
        if (arrTemp.indexOf('等') != -1) {
          arrTemp[arrTemp.length - 2] = arrTemp[arrTemp.length - 2].substr(0, arrTemp[arrTemp.length - 2].length - 1)
        } else {
          //
          arrTemp[arrTemp.length - 1] = arrTemp[arrTemp.length - 1].substr(0, arrTemp[arrTemp.length - 1].length - 1)
        }
        this.materialName = arrTemp
      }
    },
    search() {
      const arr = JSON.parse(JSON.stringify(this.selectionsAll))
      this.tableDataOne = this.tableData3.filter(item => item.materialCode && item.materialCode.indexOf(this.pageData.searchValue) !== -1 || item.saleOrderCode && item.saleOrderCode.indexOf(this.pageData.searchValue) !== -1)
      this.tableData = this.tableDataOne
      this.$nextTick(() => {
        this.selectionsAll = arr
        this.setSelectRow(this)
        // this.selectionsAll.forEach(ele => {
        //   this.$refs.table.toggleRowSelection(ele, true)
        // })
      })
    },
    cancel() {
      this.$layer.close(this.layerid)
    },
    onSubmit() {
      this.selectionsAll.sort(function(a, b) {
        return b.materialId - a.materialId
      })
      console.log(this.selectionsAll)
      this.$parent.showListData(this.selectionsAll)
      this.$layer.close(this.layerid)
    }
  }
}
</script>

<style lang="less" scoped>
.button{
    width: 100px;
    height: 30px;
    color: #fff;
    background-color: #387bfc;
    border-radius: 4px;
    text-align: center;
    line-height: 30px;
}
.main_search_item{
  padding-right: 20px !important;
}
.main_main_search{
  padding-right: 20px !important;
}
.main_main_search_item{
  padding-left: 20px !important;
}
.main_main{
  margin:0 !important;
  padding-top:0 !important;
}
.button_icon{
 background:#387bfc;
 width:30px;
}
.search_input{
  width:200px;
  margin-right:10px
}
.table_container{
  margin: 0 !important;
}
.addtype-main_bottoms{
  padding-right: 20px !important;
  margin: 10px 0;
}
/deep/ .el-input--suffix .el-input__inner {
    padding-right:25px;
}
.MaterialName {
  display: flex;
  color:rgb(244,156,31);
  justify-content: flex-end;
  align-items: center;
  font-size: 16px;
  padding-top: 20px;
  padding-left: 15px;
  .MaterialNameIcon {
    display: flex;
    align-items: center;
    justify-content: center;
    padding-top: 1px    ;
    padding-left: 2px;
    padding-right: 5px;
  }
}
/deep/.el-table__body-wrapper{
  border-bottom: 1px solid #dcdfe6;
}
</style>
